package com.huanglejing.shanggou.activity

import android.os.Bundle
import android.support.v4.util.ArrayMap
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import com.google.gson.JsonObject
import com.huanglejing.mylibrary.KLog
import com.huanglejing.shanggou.R
import com.huanglejing.shanggou.adapter.SellersAdapter
import com.huanglejing.shanggou.bean.CompanyListBean
import com.huanglejing.shanggou.bean.GoodsListBean
import com.huanglejing.shanggou.common.AppBaseActivity
import com.huanglejing.shanggou.common.AppContext
import com.huanglejing.shanggou.data.*
import com.huanglejing.shanggou.greendao.CacheGoodsBean
import com.huanglejing.shanggou.greendao.CacheOrderBean
import com.huanglejing.shanggou.interfaces.IonSlidingViewClickListener
import com.huanglejing.shanggou.interfaces.MineSellersContract.MineSellersPresenter
import com.huanglejing.shanggou.interfaces.MineSellersContract.MineSellersView
import com.huanglejing.shanggou.presenterimpl.MineSellersImpl
import com.huanglejing.shanggou.rx.event.CompanyRefreshEvent
import com.huanglejing.shanggou.rx.rxbus.RxBus
import com.huanglejing.shanggou.utils.C
import com.huanglejing.shanggou.utils.CacheLoader
import com.huanglejing.shanggou.utils.ToastUtils
import com.huanglejing.shanggou.utils.UIHelper
import com.jcodecraeer.xrecyclerview.ProgressStyle
import com.jcodecraeer.xrecyclerview.XRecyclerView
import kotlinx.android.synthetic.main.activity_mine_sellers.*
import kotlinx.android.synthetic.main.main_head_blue.*
import rx.Observable

class MineSellersActivity : AppBaseActivity<MineSellersPresenter<MineSellersView>, MineSellersView>(), MineSellersView, XRecyclerView.LoadingListener
        , IonSlidingViewClickListener {
    var mData: ArrayList<CompanyListBean>? = arrayListOf();
    var myAdapter: SellersAdapter? = null
    private var deleteId: String? = null
    private val mEmptyView by lazy {
        mRootView?.findViewById<View>(R.id.ll_xr_empty)
    }
    private val mErrorView by lazy {
        mRootView?.findViewById<View>(R.id.ll_xr_error)
    }

    override fun getRequestParams(): Observable<Map<String, Any>> {
        val map = ArrayMap<String, String>().apply {
            put("customerId", CacheCustomerId ?: "")
        }
        return Observable.just(map)
    }

    override fun getDeleteParams(): Observable<Map<String, Any>> {
        val map = ArrayMap<String, String>().apply {
            put("customerId", CacheCustomerId ?: "")
            put("companyId", deleteId ?: "")
        }
        return Observable.just(map)
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initWidget()
    }

    private fun initWidget() {

        setAPPTitle(resources.getString(R.string.str_my_shops))
        iv_save_address?.visibility = View.VISIBLE
        iv_save_address.setOnClickListener {
            ToastUtils.toastLong(resources.getString(R.string.str_add_shops))
            UIHelper.startActivity(AddSellerActivity::class.java)
        }
        xr_mine_sellers_list?.setLoadingListener(this@MineSellersActivity)
        xr_mine_sellers_list?.setLoadingMoreProgressStyle(ProgressStyle.BallRotate)
        xr_mine_sellers_list?.setRefreshProgressStyle(ProgressStyle.BallRotate)

        xr_mine_sellers_list.layoutManager = LinearLayoutManager(this@MineSellersActivity)
        myAdapter = SellersAdapter(this@MineSellersActivity, mData)
        xr_mine_sellers_list.adapter = myAdapter
//        xr_mine_sellers_list.addHeaderView(mHeaderView)
//        mHeaderView.setOnClickListener {
//
//        }
        //
    }

    override fun onResume() {
        super.onResume()
        showContent(getCacheCompanyList() ?: arrayListOf())
    }

    override fun createPresenter(): MineSellersPresenter<MineSellersView> = MineSellersImpl()

    override fun getLayoutId(): Int = R.layout.activity_mine_sellers

    override fun requestPermission() {
    }

    override fun <T> showContent(data: T?) {
        try {
            val mNetData = data as? ArrayList<CompanyListBean>
            if (mNetData != null && mData != null) {
                mData?.clear()
                mData?.addAll(mNetData ?: arrayListOf())
                if (mData?.size?:0<1 && mEmptyView!=null){
                    xr_mine_sellers_list?.emptyView=mEmptyView
                }
                myAdapter?.setData(mData)
                myAdapter?.notifyDataSetChanged()
            }
            loadComPlete()
        } catch (e: Exception) {
            KLog.e(e?.message)
        }

    }


    override fun showDeleteSuccess(t: Any) {
        if (t is JsonObject) {
            if (t?.get("status")?.asString?.equals("00") ?: false ) {
                ToastUtils.toastLong(resources.getString(R.string.str_delete_sellers_success))
                RxBus.get().postEvent(CompanyRefreshEvent())
                GOODSLIST?.clear()
                CacheLoader.acache.put(C.Cache.GOODS_LIST, arrayListOf<GoodsListBean>())
                AppContext.get().companyId=""
                var bean:CompanyListBean?=null
                COMPANYLIST?.forEach {
                    if (it.companyId.equals(deleteId)){
                        bean=it
                    }
                }
                COMPANYLIST?.remove(bean)
                CacheLoader.acache.put(C.Cache.COMPANY_LIST, COMPANYLIST)
                var deleteGoodsList= arrayListOf<CacheGoodsBean>()
                getCacheGoods()?.forEach {
                    if (it.companyId?.equals(deleteId)?:false){
                        deleteGoodsList?.add(it)
                    }
                }
                deleteGoodsList?.forEach {
                    beanDao?.delete(it)
                }

                var deleteList= arrayListOf<CacheOrderBean>()
                getCacheOrders()?.forEach {
                    if (it.companyId?.equals(deleteId)?:false){
                        deleteList?.add(it)
                    }
                }
                deleteList?.forEach {
                    orderDao?.delete(it)
                }
              var   deleteCompanyBen:CompanyListBean?=null
                mData?.forEach {
                    if (it.companyId?.equals(deleteId)?:false){
                        deleteCompanyBen=it
                    }
                }
                mData?.remove(deleteCompanyBen)
               showContent(mData)
             //  mBasePresenter?.getCompanyList()
            }else{
                ToastUtils.toastLong(t?.get("message")?.asString?:"")
            }
        }
    }

    override fun showError(e: Throwable?) {
        KLog.e(e?.message)
        mData?.clear()
        if (mErrorView!=null){
            xr_mine_sellers_list?.emptyView=mErrorView
            mErrorView?.setOnClickListener {
                mBasePresenter?.getCompanyList()
            }
        }

        myAdapter?.setData( mData)
        loadComPlete()
    }

    override fun onRefresh() {
        xr_mine_sellers_list?.setNoMore(false)
        showContent(getCacheCompanyList() ?: arrayListOf())
    }

    override fun onLoadMore() {
    }

    fun loadComPlete() {
        xr_mine_sellers_list?.loadMoreComplete()
        xr_mine_sellers_list?.refreshComplete()
        xr_mine_sellers_list?.setNoMore(true)
    }

    override fun onItemClick(view: View?, position: Int) {

    }

    override fun onDeleteBtnCilck(view: View?, position: Int) {
        deleteId = mData?.get(position)?.companyId?.toString()
        mBasePresenter?.deleteSellers()
    }

    override fun onSetBtnCilck(view: View?, position: Int) {
    }
}
